package com.szt.sy.util.web;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/***
 * cookie 工具类
 * 
 * @author wwy
 *
 */
public class CookieUtil {
	
	/***
	 * 添加cookie
	 *
	 * @param response
	 * @param name
	 * @param value
	 * @param expiry
	 */
	public static void addCookie(HttpServletResponse response, String name, String value, int expiry) {
		Cookie cookie = new Cookie(name, value);
		cookie.setMaxAge(expiry);
		response.addCookie(cookie);
	}
	
	/***
	 * 删除cookie
	 *
	 * @param response
	 * @param name
	 */
	public static void removeCookie(HttpServletResponse response, HttpServletRequest request, String name) {
		Cookie cookie = getCookie(request, name);
		cookie.setMaxAge(0);
		response.addCookie(cookie);
	}
	
	/***
	 * 获得cookie
	 *
	 * @param request
	 * @param name
	 * @return
	 */
	public static Cookie getCookie(HttpServletRequest request, String name) {
		Map<String, Cookie> cookieMap = readCookieMap(request);
		if (cookieMap.containsKey(name)) {
			Cookie cookie = cookieMap.get(name);
			return cookie;
		} else {
			return null;
		}
	}
	
	private static Map<String, Cookie> readCookieMap(HttpServletRequest request) {
		Map<String, Cookie> cookieMap = new HashMap<>(20);
		Cookie[] cookies = request.getCookies();
		if (null != cookies) {
			for (Cookie cookie : cookies) {
				cookieMap.put(cookie.getName(), cookie);
			}
		}
		return cookieMap;
	}
}
